package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //对密码进行md5加密以后 密码比对
         password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    /**
     * 新增员工
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDto) {
//            获得线程的id
    System.err.println("当前线程的id："+Thread.currentThread().getId());
        Employee employee =new Employee();
//        对象数据拷贝
        BeanUtils.copyProperties(employeeDto,employee);
//        设置账号的状态
        employee.setStatus(StatusConstant.ENABLE);
//        设置密码，默认密码是123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        设置当前记录的时间和修改的时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        设置当前记录人和修改人的id
//        获取线程中储存的id的值
//        Long currentId = BaseContext.getCurrentId();
//        employee.setCreateUser(currentId);
//        employee.setUpdateUser(currentId);
        employeeMapper.addEmployee(employee);

    }


    /**
     * 分页查询员工信息
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult getEmployeeByPage(EmployeePageQueryDTO employeePageQueryDTO) {
        // 使用mybatis-plus提供的分页插件
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> employeeByPage = employeeMapper.getEmployeeByPage(employeePageQueryDTO);

        long total = employeeByPage.getTotal();
        List<Employee> result = employeeByPage.getResult();

        return new PageResult(total,result);
    }


    /**
     * 启用禁用员工账号
     */
    @Override
    public void statusOrStop(Integer status, Long id) {
        System.out.println("当前线程的id："+Thread.currentThread().getId());
//        通过 builder 给 id 和status 赋值
        Employee employee= Employee.builder()
//                .id(id).status(status)
//                .updateUser(BaseContext.getCurrentId())
//                .updateTime(LocalDateTime.now())
                .build();
        System.err.println(employee.toString());
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询用户的信息
     * @param id  用户的id
     * @return
     */
    @Override
    public Employee getByEmployeeId(Long id) {
        Employee employee = employeeMapper.getByEmployeeId(id);
        employee.setPassword("***");
        return employee;
    }

//    修改员工的信息
    @Override
    public void update(EmployeeDTO employeeDto) {
        Employee  employ =new Employee();
//        拷贝对象
        BeanUtils.copyProperties(employeeDto,employ);
//        设置修改人 和修改时间
//        employ.setUpdateUser(BaseContext.getCurrentId());
//        employ.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employ);
    }

}
